import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class BasicMessageChannelPage extends StatefulWidget {
  const BasicMessageChannelPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return BasicMessageChannelPageState();
  }
}

///代码清单9-4
///lib/BasicMessageChannelPage.dart
class BasicMessageChannelPageState extends State<BasicMessageChannelPage> {
  //创建MethodChannel
  // 参数一 flutter_and_native_101 为通信标识
  // 参数二 codec 为参数传递的 编码方式，必选
  // 参数三  binaryMessenger 为使用的消息通道默认为
  //    [ServicesBinding.defaultBinaryMessenger]
  static const messageChannel =
      BasicMessageChannel('flutter_and_native_100', StandardMessageCodec());

  String _result = "";

  @override
  void initState() {
    super.initState();
    messageChannel.setMessageHandler((result) async {
      if (result != null&&result is Map) {
        //解析 原生发给 Flutter 的参数
        int code = result["code"];
        String message = result["message"];
        setState(() {
          _result = "receiveMessage: code:$code message:$message";
        });
      }
      return 'Flutter 已收到消息';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [buildTextButton()],
        ),
      ),
    );
  }
  ///代码清单9-4-1
  buildTextButton() {
    return TextButton(
      onPressed: () async {
        //发送消息
        dynamic result = await sendMessage(arguments: {"method": "test"});
        //回执消息
        if (result != null) {
          _result = result['message'].toString();
          setState(() {});
        }
      },
      child: Text("发送消息 $_result"),
    );
  }

  ///使用 messageChannel 发送消息
  Future<Object?> sendMessage({required Map arguments}) async {
    Object? reply = await messageChannel.send(arguments);
    if (reply != null && reply is Map) {
      //解析 原生发给 Flutter 的参数
      int code = reply["code"];
      String message = reply["message"];
      //更新 Flutter 中页面显示
      setState(() {
        _result = "code:$code message:$message";
      });
    }
    return reply;
  }
}
